from typing import List

from memoryscope.constants.common_constants import RETRIEVE_MEMORY_NODES, RESULT
from memoryscope.core.utils.datetime_handler import DatetimeHandler
from memoryscope.core.worker.memory_base_worker import MemoryBaseWorker
from memoryscope.enumeration.memory_type_enum import MemoryTypeEnum
from memoryscope.enumeration.store_status_enum import StoreStatusEnum
from memoryscope.scheme.memory_node import MemoryNode
from memoryscope.web.memory_res import MemoryRes


class ReturnMemoryWorker(MemoryBaseWorker):
    """
    Formats the memories to print.
    """
    FILE_PATH: str = __file__

    def _run(self):
        """
        Executes the primary function, it involves:
        1. Fetches the memories.
        2. Formats them by 'print_template'.
        3. Set the formatted string back into the worker's context
        """
        # get long-term memory
        memory_node_list: List[MemoryNode] = self.memory_manager.get_memories(RETRIEVE_MEMORY_NODES)
        memory_node_list = sorted(memory_node_list, key=lambda x: x.timestamp, reverse=True)
        # 将memory_node_list 转为 MemoryRes
        memory_res_list = []
        for node in memory_node_list:
            if not node.content:
                continue
            memory_res = MemoryRes(
                memory_id=node.memory_id,
                user_name=node.user_name,
                target_name=node.target_name,
                content=node.content,
                dt=node.dt,
                memory_type=node.memory_type,
            )
            memory_res_list.append(memory_res)

        self.set_workflow_context(RESULT, memory_res_list)
